'use strict';
const { Service } = require('egg');
const moment = require('moment');

class UserService extends Service {

  /**
   * 
   * @returns 查询
   */
  async findAll() {
    const { ctx } = this;
    let { pageSize, page } = ctx.request.body;
    page =  page - 1 >= 0 ? page - 1 >= 0 : 0;
    try {
      const userList = await ctx.model.Users.findAll({
        // where: {
        //   name: {
        //     [Op.like]: '张%'
        //   }
        // },
        limit: pageSize,
        offset: page
      });
      return userList;
    } catch (err) {
      ctx.helper.renderFail( ctx, { message: err, data: err });
    }
  }

  /**
   * @param name 用户名
   * @param id_name 证件号
   * @param password 密码
   * @returns 新增用户信息
   */
  async addOne() {
    const { ctx } = this;
    const addData = ctx.request.body;
    const { id_name } = addData;
    try {
      const findInfo = await ctx.model.Users.findOne({
        where: {
          id_name
        }
      })
      if (findInfo) {
        ctx.helper.renderFail(ctx, { message: '证件号已存在' })
      } else {
        const { name, id_name, password, age, gender, province_code, city_code, county_code, address } = ctx.request.body;
        const addedInfo = await ctx.model.Users.create({ name, id_name, password, age, gender, province_code, city_code, county_code, address });
        return addedInfo;
      }
    } catch (err) {
      ctx.helper.renderFail(ctx, { message: err, data: err });
    }
  }

  /**
   * @returns 批量添加
   */
  async addGroup() {
    const { ctx } = this;
    const dataList = ctx.request.body;
    try {
      const addedGroup = ctx.model.Users.bulkCreate(dataList, 
      { fields: ['name', 'id_name', 'password' ]});
      return addedGroup;
    } catch( err ) {
      ctx.helper.renderFail( ctx, { message: err, data: err })
    }
  }

  /**
   * @returns 删除信息
   */
  async deleteOne() {
    const { ctx } = this;
    const { uuid } = ctx.request.body;
    try {
      const exitOne = ctx.model.Users.findByPk(uuid);
      if(exitOne) {
        return exitOne;
      } else {
        ctx.helper.renderFail( ctx, { message: '查无此人'});
      }
    } catch(err) {
      ctx.helper.renderFail(ctx, { message: err, data: err });
    }
  }

  async editOne() {
    const { ctx } = this;
    const { uuid } = this.ctx.request.body;
    try {
      const editInfo =  ctx.model.Users.findByPk(uuid);
      if(editInfo) {
        // ctx.model.Users.update
      } else {
        ctx.helper.renderFail(ctx, { message: 'message not avaliable' });
      }
    } catch (err) {
      ctx.helper.renderFail(ctx, { message: err, data: err });
    }
  }
}

module.exports = UserService;
